package com.ruixin.parser;

import com.ruixin.annotation.Parser;
import com.ruixin.base.BaseParser;
import com.ruixin.base.exception.BaseException;
import com.ruixin.base.proxy.ProxyHelper;
import com.ruixin.base.util.BeanUtil;
import com.ruixin.base.util.StringUtil;
import com.ruixin.config.ApplicationContext;

import java.lang.annotation.Annotation;

/**
 * 解释Parser类
 */
@Parser(annotation = Parser.class)
public class AnnotationParser extends BaseParser<ApplicationContext> {

    public AnnotationParser(ApplicationContext context, Class<? extends Annotation> type) {
        super(context, type);
    }

    @Override
    public void parseClass(Class<?> clz) throws BaseException {
        super.parseClass(clz);
        if(clz!=BaseParser.class&&!BaseParser.class.isAssignableFrom(clz)){
            throw new BaseException("Parser只支持com.ruixin.base.annotation.BaseParser类型！");
        }
        Parser parser = BeanUtil.getAnnotation(clz, Parser.class);
        Class<? extends Annotation> annotation = parser.annotation();
        Object bean = this.context.getBean(clz);
        if(bean==null){
            String beanName = parser.value();
            if(StringUtil.isBlackOrNull(beanName)){
                beanName = parser.name();
                if(StringUtil.isBlackOrNull(beanName)){
                    beanName = BeanUtil.getDefaultBeanName(clz);
                }
            }
            bean = ProxyHelper.newProxyInstance(clz,this.context,annotation);
            this.context.addBean(beanName,bean);
        }
        this.context.addAnnotationParser(annotation, (BaseParser<ApplicationContext>) bean);
    }
}
